<script setup>
import { ref } from 'vue'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import {
  labelPublishService,
  labelGetDetailService,
  labelEditService
} from '@/api/label'

// 控制抽屉显示隐藏
const visibleDrawer = ref(false)

// 默认数据
const defaultForm = {
  labelName: '' // 标题
}
// 准备数据
const formModel = ref({ ...defaultForm })

// 提交
const emit = defineEmits(['success'])
const onPublish = async () => {
  // 注意：当前接口，需要的是 formData 对象
  // 将普通对象 => 转换成 => formData对象
  // 发请求
  if (formModel.value.id) {
    // 编辑操作
    await labelEditService(formModel.value)
    ElMessage.success('修改成功')
    visibleDrawer.value = false
    emit('success', 'edit')
  } else {
    // 添加操作
    await labelPublishService(formModel.value)
    ElMessage.success('添加成功')
    visibleDrawer.value = false
    // 通知到父组件，添加成功了
    emit('success', 'add')
  }
}
const handleClose = async () => {}

// 组件对外暴露一个方法 open，基于open传来的参数，区分添加还是编辑
// open({})  => 表单无需渲染，说明是添加
// open({ id, ..., ... })  => 表单需要渲染，说明是编辑
// open调用后，可以打开抽屉
const open = async (row) => {
  visibleDrawer.value = true // 显示抽屉

  if (row.id) {
    // 需要基于 row.id 发送请求，获取编辑对应的详情数据，进行回显
    const res = await labelGetDetailService(row.id)
    formModel.value = res.data.data
  } else {
    formModel.value = { ...defaultForm } // 基于默认的数据，重置form数据
  }
}

defineExpose({
  open
})
</script>

<template>
  <el-dialog
    :title="formModel.id ? '编辑标签' : '添加标签'"
    v-model="visibleDrawer"
    width="30%"
    @close="handleClose"
  >
    <el-form label-position="right" label-width="60px" :model="formModel">
      <el-form-item label="名称">
        <el-input v-model="formModel.labelName"></el-input>
      </el-form-item>
    </el-form>
    <div class="dialog-footer">
      <el-button @click="visibleDrawer.value = false">取 消</el-button>
      <el-button type="primary" @click="onPublish">确 定</el-button>
    </div>
  </el-dialog>
</template>

<style lang="scss" scoped>
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}
</style>
